package com.cham.pdm.controller;

import com.cham.enums.ChamSysCodeEnum;
import com.cham.login.dto.LoginResultDTO;
import com.cham.pdm.service.UserService;
import com.cham.token.dto.TokenVerify;
import com.cham.user.entity.User;
import com.cham.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * @author Howl-Xu
 * @version 1.0.0
 * @Description: 请描述一下这个类文件吧
 * @createTime 2020年03月14日 11:30:00
 */
@Controller
@RequestMapping("/loginController")
public class LoginController {
    @Autowired
    private UserService userService;

    @GetMapping("/login")
    @ResponseBody
    public LoginResultDTO login(String account, String password){
        User user = userService.getUserByAccountAndPassword(account,password);
        boolean isAccountExist = user!=null;
        LoginResultDTO result = new LoginResultDTO();

        //登录成功的代码逻辑
        if(isAccountExist)
        {
            //登陆成功,添加状态码
            result.setChamCode(ChamSysCodeEnum.SUCCESS.getChamCode());
            result.setChamCodeDesc(ChamSysCodeEnum.SUCCESS.getChamCodeDesc());
            result.setUserHeadImg(userService.getUserHeadImgByUUID(user.getUserUuid()));
            //使用账号和uuid以及token生成器生成一个token
            String chaosToken = TokenUtils.sign(user.getAccount(),user.getUserUuid());
            result.setChamToken(TokenUtils.sign(user.getAccount(),user.getUserUuid()));
        }

        //登录失败的代码逻辑
        if(!isAccountExist)
        {
            //登陆失败，也添加状态码
            result.setChamCode(ChamSysCodeEnum.ERROR01.getChamCode());
            result.setChamCodeDesc(ChamSysCodeEnum.ERROR01.getChamCodeDesc());
        }
        return result;

    }

    @PostMapping("/verifyToken")
    @ResponseBody
    public boolean verifyToken(@RequestBody TokenVerify TokenVerify){
        return TokenUtils.verify(TokenVerify.getToken());
    }
}
